// Copyright (c) 2012 Andrei Rinea
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;

namespace BenchmarkNet
{
    public class Benchmark
    {
        public static BenchmarkResult Sequential<TState>(BenchmarkParams<TState> @params, TState state = null) where TState : class
        {
            var action = @params.Action;
            var iterations = @params.Iterations;
            uint index = 0;
            bool success;

            var stopwatch = Stopwatch.StartNew();
            try
            {
                for (; index < iterations; index++) action(state);
                success = true;
            }
            catch { success = false; }
            finally { stopwatch.Stop(); }

            return new BenchmarkResult(stopwatch.Elapsed, index, success);
        }

        public static BenchmarkResult Sequential(Action action, uint iterations)
        {
            return Sequential(new BenchmarkParams(action, iterations));
        }

        public static BenchmarkResult Sequential(Action action)
        {
            return Sequential(action, 1);
        }

        public static BenchmarkResult Parallel<TState>(BenchmarkParams<TState> benchmarkParams, byte threadCount,
            Func<TState> stateGenerator = null, TimeSpan? totalTimeout = null) where TState : class
        {
            if (benchmarkParams == null) throw new ArgumentNullException("benchmarkParams");
            if (threadCount == 0) throw new ArgumentOutOfRangeException("threadCount");

            var statistics = new ParallelBenchmark<TState>[threadCount];
            for (byte threadIndex = 0; threadIndex < threadCount; threadIndex++)
            {
                var thread = new Thread(ParallelBenchmark<TState>.DoWork);
                var state = stateGenerator != null ? stateGenerator() : null;
                var benchmark = new ParallelBenchmark<TState>(benchmarkParams, state);
                statistics[threadIndex] = benchmark;
                thread.Start(benchmark);
            }

            var waitHandles = statistics.Select(s => s.WaitHandle).ToArray();
            if (totalTimeout.HasValue) WaitHandle.WaitAll(waitHandles, totalTimeout.Value);
            else WaitHandle.WaitAll(waitHandles);

            return BenchmarkResult.Aggregate(statistics.Select(s => s.Result));
        }

        public static BenchmarkResult Parallel<TState>(Action<TState> action, uint iterations, byte threadCount) where TState : class
        {
            return Parallel(new BenchmarkParams<TState>(action, iterations), threadCount);
        }

        public static BenchmarkResult Parallel(Action action, byte threadCount)
        {
            if (action == null) throw new ArgumentNullException("action");

            return Parallel<object>(_ => action(), 1, threadCount);
        }
    }
}